package com.hejia.alauda.persistence.mybatis;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.hejia.alauda.entity.Order;
import com.hejia.alauda.persistence.BaseMapper;

public interface OrderMapper extends BaseMapper<Order> {
	@Update("UPDATE `order` SET `orderLock`=1 WHERE `orderLock`=0 AND `id`=#{id}")
	int updateLockOrderById(Long id);
	
	@Update("UPDATE `order` SET `orderLock`=0 WHERE `orderLock`=1 AND `id`=#{id}")
	int updateReleaseOrderById(Long id);
	
	@Update("update `order` set status=\'STATUS_OVERDUE\',modifyDate=now() where TIMESTAMPDIFF(SECOND,createDate,now())>600 and id=#{id} and `status`=\'STATUS_UNPAY\'")
	int updateOrderStatusOverdue(Long id);

	@Update("update `order` set status=\'STATUS_OVERDUE\',modifyDate=now() where id=#{id} and `status`=\'STATUS_UNPAY\'")
	int updateOrderStatusOverdueImmediately(Long id);

	@Update("update `order` set status=#{changeStatus},modifyDate=now() where orderNumber=#{orderNumber} and `status`=#{whereStatus}")
	int updateOrderStatusImmediately(@Param("orderNumber") String orderNumber,
			@Param("changeStatus") String changeStatus,
			@Param("whereStatus") String whereStatus);

	@Update("update `order` set `tag`=#{tag} where id=#{id} and `tag` IS NULL")
	int updateOrderTag(Order order);

	/**
	 * 根据订单编号、手机号码和订单时间查询订单
	 * 
	 * @param map
	 *            查询条件
	 * @return 订单
	 */
	List<Order> selectOrders(Map<String, Object> map);

	/**
	 * 根据订单编号、手机号码和订单时间查询订单数量
	 * 
	 * @param map
	 *            查询条件
	 * @return 订单数量
	 */
	int selectOrdersCount(Map<String, Object> map);
	
	/**
	 * 日订单销量总额和总成交笔数
	 *
	 * @param status
	 * @param date
	 * @return
	 */
	Map<String, Object> dayTotalSalesAndOrders(Order.Status status, String date);

	@Select("select count(*) from (select *, if(status='STATUS_OVERDUE'||status='STATUS_FAILED', @failCount:=@failCount+1,@failCount:=0) as failCount from (select * from `order` a where createDate > date_sub(now(), interval 15 MINUTE) order by id) oo, (select @failCount:=0) as fc) fo where fo.failCount >= #{number}")
	int checkFailOrders(int number);

	@Select("select distinct b.bankName from `order` o join bankcard b on o.bankcard_id = b.id where o.createDate > date_sub(now(), interval 5 MINUTE)")
	List<String> getOrderBankNames();

	@Select("select count(*) from (select *,if(status='STATUS_OVERDUE'||status='STATUS_FAILED',@failCount:=@failCount+1,@failCount:=0) as failCount from (select o.*, b.bankName from `order` o join bankcard b on o.bankcard_id = b.id where b.bankName=#{bankName} and o.createDate > date_sub(now(), interval 5 MINUTE) order by o.id) oo, (select @failCount:=0) as fc) fo where fo.failCount >= #{orderFailNumber}")
	int checkFailOrderBanks( 
			@Param("bankName") String bankName, 
			@Param("orderFailNumber") int orderFailNumber);

	/**
	 * 查询银行卡关联的未回款订单
	 * @param bankCardId	银行卡ID
	 * @return 订单列表
	 */
	List<Order> findNotRepaymentOrdersByBankCardId(Long bankCardId);
	
	/**
	 * 获取订单的到期日
	 * 
	 * @param id
	 * @return
	 */
	@Select("select f.`settlementDate` from `order` o ,`financing` f where o.id = f.`order_id` and f.`order_id` = #{0}")
	@ResultType(value = Date.class)
	Date getOrderSettlementDate(Long id);

	/**
	 * 更新订单支付状态
	 * @param orderId	订单ID
	 * @param payGateStatus 支付网关支付状态
	 * @return
	 */
	@Update("update `order` set modifyDate = now(), payGateStatus = #{payGateStatus} where id = #{orderId}")
	int updateOrderPayGateStatus(
			@Param("orderId") Long orderId, 
			@Param("payGateStatus") String payGateStatus);

	/**
	 * 查询未同步支付最终状态订单ID列表
	 * @param startTime	查询开始时间
	 * @return 未同步支付最终状态订单ID列表
	 */
	@Select("select id from `order` where createDate >= #{startTime} and status = 'STATUS_OVERDUE'")
	List<Long> findNotSyncPayStatusOrderIds(@Param("startTime") Date startTime);
	
	@Select("select o.* from `order` o where o.status = 'STATUS_PAID' and o.user_id = #{userId} and createDate > #{date} order by id desc")
	List<Order> findPaidOrdersByUserIdAndDate(@Param("userId") Long userId, @Param("date") Date date);

	/**
	 * 查询超额支付订单
	 * @param pager 
	 * @param keyword 关键词
	 * @param date 下单日期
	 * @param refund 是否退款
	 * @return	超额支付订单
	 */
	List<Order> findExcessOrders(
			@Param("startNumber") Integer startNumber, 
			@Param("pageSize") Integer pageSize, 
			@Param("keyword") String keyword, 
			@Param("date") Date date, 
			@Param("refund") Boolean refund);

	/**
	 * 统计超额支付订单
	 * @param pager 
	 * @param keyword 关键词
	 * @param date 下单日期
	 * @param refund 是否退款
	 * @return	超额支付订单数
	 */
	Integer countExcessOrders(
			@Param("keyword") String keyword, 
			@Param("date") Date date, 
			@Param("refund") Boolean refund);

	/**
	 * 更新支付网关支付状态
	 * @param payNumber 支付订单号
	 * @param payGateStatus	支付网关状态
	 * @param payGateStatusDescription 支付网关状态描述
	 * @return
	 */
	@Update("update `order` set payGateStatus = #{payGateStatus}, payGateStatusDescription = #{payGateStatusDescription} where payNumber = #{payNumber}")
	int updateOrderPayGateStatusByPayNumber(
			@Param("payNumber") String payNumber, 
			@Param("payGateStatus") String payGateStatus, 
			@Param("payGateStatusDescription") String payGateStatusDescription);

}
